/*
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * DMGIS. You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with DMGIS.
 *
 */
package com.dmgis.qxfw.dataservice.pages.controller;

import com.dmgis.qxfw.dataservice.businessservice.api.UserPermissionRequest;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.Results;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.Results1;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.Results2;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.xt.login;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.ResultObj;
import com.dmgis.qxfw.dataservice.businessservice.common.util.RandomValidateCode;
import com.dmgis.qxfw.dataservice.businessservice.common.util.StringUtil;
import com.dmgis.qxfw.dataservice.commonservice.utils.MD5Utils;
import com.dmgis.qxfw.dataservice.commonservice.utils.RedisUtil;
import com.dmgis.qxfw.dataservice.pages.entity.*;
import com.dmgis.qxfw.dataservice.pages.service.ILoginService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This class is used for 页面跳转
 *FF
 * @author dsq
 * @version 1.0, 2018年10月26日 下午3:23:04
 */
@Controller
@RequestMapping("/")
public class RedirectPage {

	@Resource
	ILoginService loginService;


	/**
	 * 跳转到指定页面根据参数
	 *
	 * @param request
	 * @param model
	 * @return
	 * @author dsq
	 * @date 2018年10月26日
	 */
	@RequestMapping("/site")
	public String GotoGtPage(HttpServletRequest request, Model model) {
		String site = request.getParameter("site");
		if (site == null && !"".equals(site)) {
			site = "error";
		} else {
			site = site + "/index";
		}
		return site;
	}

	@RequestMapping("/login")
	@ResponseBody
	public Object Login(HttpServletRequest request, Model model) {
		String userName = request.getParameter("username");
		String passWord = request.getParameter("password");
		String inputCode = request.getParameter("verification");
		String role = request.getParameter("role");
		List<login> result = null;
		//用户名密码判断
		if (!StringUtil.IsNullOrEmpty(role)) {
			//查询农业大户 农业局
			if ("农业大户".equals(role) || "农业局".equals(role)) {
				result = loginService.CheckLoginNy(userName, passWord, role);
			} else if ("信息员".equals(role)) {
				result = loginService.CheckLoginInfo(userName, passWord, role);
			} else if ("协理员".equals(role)) {
				result = loginService.CheckLoginHelp(userName, passWord, role);
			}
		} else {
			Jedis jedis = RedisUtil.getJedis();
			String verification = "";
			if (!StringUtil.IsNullOrEmpty(inputCode)) {
				verification = jedis.get(inputCode.toUpperCase());
			}
			//判断验证码是否正确
			if (!StringUtil.IsNullOrEmpty(inputCode) && !inputCode.toUpperCase().equals(verification)) {
				RedisUtil.returnBrokenResource(jedis);
				return new ResultObj("验证码错误", "-1", false);
			}
			result = loginService.CheckLogin(userName, passWord);

			jedis.close();
		}
		if ("-1".equals(result.get(0).getUrl())) {
			return new ResultObj("用户名不存在", null, false);// 用户名不存在;
		} else if ("-2".equals(result.get(0).getUrl())) {
			return new ResultObj("密码错误", null, false);// 密码错误
		}
		else if ("-3".equals(result.get(0).getUrl())) {
			return new ResultObj("没有权限", null, false);// 没有权限
		}else if ("-4".equals(result.get(0).getUrl())) {
			return new ResultObj("用户名或密码错误", null, false);// 用户名或密码错误
		} else {
			request.getSession().setAttribute("userName", userName);
			request.getSession().setAttribute("wbSite", result.get(0).getUrl());
			request.getSession().setAttribute("permission",result.get(0).getStrRole());
//			strResult = "{\"result\":\"success\",\"msg\":\"" + result + "\"}";
			return new ResultObj("查询成功", result, true);
		}
	}

	@RequestMapping("/login1")
	@ResponseBody
	public Object Login1(HttpServletRequest request, Model model) {
		String userName = request.getParameter("username");
		String passWord = request.getParameter("password");
		String inputCode = request.getParameter("verification");

		String advCode = "";
		List<login> result = null;

		//用户名密码判断
		Jedis jedis = RedisUtil.getJedis();
		String verification = "";
		result = loginService.CheckLogin1(userName, passWord);
		jedis.close();
		if ("-1".equals(result.get(0).getUrl())) {
			return new ResultObj("用户名不存在", null, false);// 用户名不存在;
		} else if ("-2".equals(result.get(0).getUrl())) {
			return new ResultObj("密码错误", null, false);// 密码错误
		}
		else if ("-3".equals(result.get(0).getUrl())) {
			return new ResultObj("没有权限", null, false);// 没有权限
		}else if ("-4".equals(result.get(0).getUrl())) {
			return new ResultObj("用户名或密码错误", null, false);// 用户名或密码错误
		} else {
			request.getSession().setAttribute("userName", userName);
			request.getSession().setAttribute("wbSite", result.get(0).getUrl());
			request.getSession().setAttribute("permission",result.get(0).getStrRole());
//			strResult = "{\"result\":\"success\",\"msg\":\"" + result + "\"}";
			return new ResultObj("查询成功", result, true);
		}
	}

//
@RequestMapping("/login2")
@ResponseBody
public Results1 Login2(HttpServletRequest request, Model model) {
	String userName = request.getParameter("username");
	String passWord = request.getParameter("password");
	String type = request.getParameter("type");

	String advCode = "";
	List<SysUser> result = null;

	//用户名密码判断
	Jedis jedis = RedisUtil.getJedis();
	String verification = "";
	result = loginService.CheckLogin2(userName, passWord);

	String id = String.valueOf(result.get(0).getId());
	jedis.close();
	List<Permission> havePermissions = null;
	List<Map<String, Object>> havePermissionsList = null;

	try {
		if (type.equals("0")) {
			havePermissions = loginService.selectHavePermissionBy(id);
			havePermissionsList = formatPermissions4(havePermissions);
		}else if (type.equals("1")) {
			havePermissions = loginService.selectHavePermissionByApp(id);
			havePermissionsList = formatPermissions2(havePermissions);
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}

	if ("-1".equals(result.get(0).getUrl())) {
		return  Results1.success("用户名不存在",0, null,null);// 用户名不存在;
	} else if ("-2".equals(result.get(0).getUrl())) {
		return  Results1.success("密码错误",1, null,null);// 密码错误
	}
	else if ("-3".equals(result.get(0).getUrl())) {
		return  Results1.success("没有权限",0, null,	null);// 没有权限
	}else if ("-4".equals(result.get(0).getUrl())) {
		return  Results1.success("用户名或密码错误",1, null,null);// 用户名或密码错误
	} else {
		request.getSession().setAttribute("userName", userName);
		request.getSession().setAttribute("wbSite", result.get(0).getUrl());
//			strResult = "{\"result\":\"success\",\"msg\":\"" + result + "\"}";
		return  Results1.success("登录成功",1, result,havePermissionsList);
	}
}

	@RequestMapping("/getVerify")
	@ResponseBody
	public void getVerify(HttpServletRequest request, HttpServletResponse response){
		response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
		response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expire", 0);
		RandomValidateCode randomValidateCode = new RandomValidateCode();
		Jedis jedis =null;
		try {
			String randcode = randomValidateCode.getRandcode(request, response);//输出验证码图片方法
			//先删再存储
			jedis = RedisUtil.getJedis();
			String verification = jedis.get(randcode.toUpperCase());
			if (!StringUtil.IsNullOrEmpty(verification)) {
				jedis.del(randcode.toUpperCase());
			}
			jedis.set(randcode.toUpperCase(),randcode);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			jedis.close();
		}
	}

	@RequestMapping("/selectLikeUser")
	@ResponseBody
	public PageInfo<SysUser> selectLikeUser(HttpServletRequest request, Model model) {
		String userName = request.getParameter("userName");
		String useraccount = request.getParameter("userAccount");
		int pageNum = Integer.parseInt(request.getParameter("pageNum"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        PageHelper.startPage(pageNum,pageSize);
		try {
			return loginService.selectLikeUser(userName,useraccount,pageNum,pageSize);

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@RequestMapping("/selectAllUser")
	@ResponseBody
	public PageInfo<SysUser> selectAllUser(int pageNum , int pageSize) {
		PageHelper.startPage(pageNum,pageSize);
		try {
			return loginService.selectAllUser(pageNum,pageSize);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	@RequestMapping("/updateUserForId")
	@ResponseBody
	public Results updateUserForId(HttpServletRequest request, Model model) {
		String userName = request.getParameter("userName");
		String userAccount = request.getParameter("userAccount");
		String unit = request.getParameter("unit");
		String userLv = request.getParameter("userLv");
		String id = request.getParameter("id");
		String password = request.getParameter("password");

		if (id == null || id.isEmpty()) {
			return Results.fail("用户ID不能为空");
		}

		// 这里返回值是一个列表，但更新操作一般返回的是影响的记录数，所以你可以调整类型
		int updateCount = 0;
		try {
			// 调用更新服务，获取更新结果
			updateCount = loginService.updateUserForId(userName, userAccount, userLv, id, password, unit);

			if (updateCount > 0) {
				return Results.success("根据用户ID更新用户信息", updateCount, "更新成功");
			} else {
				return Results.fail("没有找到符合条件的用户，更新失败");
			}
		} catch (Exception e) {
			// 捕获异常并返回失败信息
			return Results.fail("更新失败，错误信息：" + e.getMessage());
		}

	}


	@RequestMapping("/deleteUserForId")
	@ResponseBody
	public Results deleteUserForId(HttpServletRequest request, Model model) {
		String id = request.getParameter("id");
		if (id == null || id.isEmpty()) {
			return Results.fail("用户ID不能为空");
		}
		// 这里返回值是一个列表，但更新操作一般返回的是影响的记录数，所以你可以调整类型
		int deleteCount = 0;
		try {
			// 调用更新服务，获取更新结果
			deleteCount = loginService.deleteUserForId(id);

			if (deleteCount > 0) {
				return Results.success("根据用户ID删除用户信息", deleteCount, "删除成功");
			} else {
				return Results.fail("没有找到符合条件的用户，删除失败");
			}
		} catch (Exception e) {
			// 捕获异常并返回失败信息
			return Results.fail("删除失败，错误信息：" + e.getMessage());
		}
	}
	@RequestMapping("/insertUserInfo")
	@ResponseBody
	public Results insertUserInfo(HttpServletRequest request, Model model) {
		String userName = request.getParameter("userName");
		String userAccount = request.getParameter("userAccount");
		String unit = request.getParameter("unit");
		String userLv = request.getParameter("userLv");
		String password = request.getParameter("password");
		// 这里返回值是一个列表，但更新操作一般返回的是影响的记录数，所以你可以调整类型
		int deleteCount = 0;
		try {
			// 调用更新服务，获取更新结果
			deleteCount = loginService.insertUserInfo(userName, userAccount, userLv, password, unit);

			if (deleteCount > 0) {
				return Results.success("新增用户信息", deleteCount, "新增成功");
			} else {
				return Results.fail("新增失败");
			}
		} catch (Exception e) {
			// 捕获异常并返回失败信息
			return Results.fail("新增失败，错误信息：" + e.getMessage());
		}
	}

	@RequestMapping("/selectAllPermission")
	@ResponseBody
	public Results2 selectAllPermission(HttpServletRequest request, Model model) {
		List<Map<String, Object>> formattedPermissions = new ArrayList<>();
        List<Map<String, Object>> havePermissionsList = new ArrayList<>();
        ArrayList<Integer> arrayList = new ArrayList<>();
		try {
			String type = request.getParameter("type");
			String id = request.getParameter("id");
           if(type.equals("0")) {
			   // 获取所有权限信息，假设返回的是一个 List<Permission> 类型的列表
			   List<Permission> allPermissions = loginService.selectAllPermission(type);
			   formattedPermissions = formatPermissions(allPermissions);
			   List<Permission> havePermissions = loginService.selectHavePermission(id);
			   havePermissionsList = formatPermissions(havePermissions);
			   arrayList = loginService.selectPermission(id,type);
		   }else if(type.equals("1")){
			   List<Permission> allPermissions = loginService.selectAllPermissionByType(type);
			   formattedPermissions = formatPermissions1(allPermissions);
			   List<Permission> havePermissions = loginService.selectHavePermissionByType(id);
			   havePermissionsList = formatPermissions1(havePermissions);
			   arrayList = loginService.selectPermission(id,type);
		   }else {
			   return Results2.fail("请输入正确的type" );
		   }

			// 返回格式化后的权限数据
			return Results2.success("查询全部权限信息", 200, formattedPermissions,havePermissionsList,arrayList);
		} catch (Exception e) {
			// 捕获异常并返回失败信息
			return Results2.fail("查询失败，错误信息：" + e.getMessage());
		}
	}

	@RequestMapping("/insertUserPermission")
	@ResponseBody
	public Results insertUserPermission(@RequestBody UserPermissionRequest request) {
		String userId = request.getUserId();
		List<Integer> permissionIds = request.getPermissionId(); // 插入
		List<Integer> deletePermissionIds = request.getDeletePermissionId(); // 删除

		// 如果没有插入和删除权限，直接返回失败
		if ((permissionIds == null || permissionIds.isEmpty()) && (deletePermissionIds == null || deletePermissionIds.isEmpty())) {
			return Results.fail("没有需要操作的权限信息");
		}

		int insertCount = 0;
		int deleteCount = 0;

		// 如果有删除权限，进行删除
		if (deletePermissionIds != null && !deletePermissionIds.isEmpty()) {
			try {
				deleteCount = loginService.deleteUserPermissionForId(userId, deletePermissionIds);
				if (deleteCount <= 0) {
					return Results.fail("删除失败");
				}
			} catch (Exception e) {
				return Results.fail("删除失败，错误信息：" + e.getMessage());
			}
		}

		// 如果有插入权限，进行插入
		if (permissionIds != null && !permissionIds.isEmpty()) {
			try {
				insertCount = loginService.insertUserPermission(userId, permissionIds);
				if (insertCount > 0) {
					return Results.success("更新用户权限信息", insertCount, "操作成功");
				} else {
					return Results.fail("新增权限失败");
				}
			} catch (Exception e) {
				return Results.fail("新增权限失败，错误信息：" + e.getMessage());
			}
		}

		// 如果仅进行了删除操作
		if (deleteCount > 0 && (permissionIds == null || permissionIds.isEmpty())) {
			return Results.success("删除成功", deleteCount, "删除成功");
		}

		// 如果仅进行了插入操作
		if (insertCount > 0 && (deletePermissionIds == null || deletePermissionIds.isEmpty())) {
			return Results.success("插入成功", insertCount, "插入成功");
		}

		// 如果两者都有操作，返回总的成功信息
		return Results.success("操作成功", insertCount + deleteCount, "操作成功");
	}

	private List<Map<String, Object>> formatPermissions(List<Permission> allPermissions) {
		List<Map<String, Object>> result = new ArrayList<>();

		// 遍历所有权限数据，按层级组织
		for (Permission permission : allPermissions) {
			// 查找或创建一级权限
			Map<String, Object> level1 = findOrCreateLevel(permission.getLevel1Id(), permission.getLevel1Title(),result);

			// 查找或创建二级权限
			Map<String, Object> level2 = findOrCreateLevel(permission.getLevel2Id(), permission.getLevel2Title(),(List<Map<String, Object>>) level1.get("children"));

			// 创建三级权限
			Map<String, Object> level3 = new HashMap<>();
			level3.put("id", permission.getLevel3Id());
			level3.put("label", permission.getLevel3Title());

			// 将三级权限添加到二级权限的 children 中
			List<Map<String, Object>> level2Children = (List<Map<String, Object>>) level2.get("children");
			level2Children.add(level3);
		}

		return result;
	}

	// 查找或创建一级或二级权限
	private Map<String, Object> findOrCreateLevel4( int id, String name, String image, List<Map<String, Object>> parentList) {
		// 查找是否已经存在该权限
		for (Map<String, Object> level : parentList) {
			if ((int) level.get("id") == id) {
				return level;
			}
		}

		// 如果没有找到，则创建新的权限
		Map<String, Object> newLevel = new HashMap<>();
		newLevel.put("id", id);
		newLevel.put("name", name);
		newLevel.put("path", image);
		newLevel.put("children", new ArrayList<Map<String, Object>>()); // 初始化 children
		parentList.add(newLevel);

		return newLevel;
	}

	private List<Map<String, Object>> formatPermissions4(List<Permission> allPermissions) {
		List<Map<String, Object>> result = new ArrayList<>();

		// 遍历所有权限数据，按层级组织
		for (Permission permission : allPermissions) {
			// 查找或创建一级权限
			Map<String, Object> level1 = findOrCreateLevel(permission.getLevel1Id(), permission.getLevel1Title(),result);

			// 查找或创建二级权限
			Map<String, Object> level2 = findOrCreateLevel4(permission.getLevel2Id(), permission.getLevel2Title(),permission.getLevel2Image(),(List<Map<String, Object>>) level1.get("children"));

			// 创建三级权限
			Map<String, Object> level3 = new HashMap<>();
			level3.put("id", permission.getLevel3Id());
			level3.put("image", permission.getLevel3Image());
			level3.put("name", permission.getLevel3Title());

			// 将三级权限添加到二级权限的 children 中
			List<Map<String, Object>> level2Children = (List<Map<String, Object>>) level2.get("children");
			level2Children.add(level3);
		}

		return result;
	}

	// 查找或创建一级或二级权限
	private Map<String, Object> findOrCreateLevel( int id, String label,List<Map<String, Object>> parentList) {
		// 查找是否已经存在该权限
		for (Map<String, Object> level : parentList) {
			if ((int) level.get("id") == id) {
				return level;
			}
		}

		// 如果没有找到，则创建新的权限
		Map<String, Object> newLevel = new HashMap<>();
		newLevel.put("id", id);
		newLevel.put("label", label);
		newLevel.put("children", new ArrayList<Map<String, Object>>()); // 初始化 children
		parentList.add(newLevel);

		return newLevel;
	}


	private List<Map<String, Object>> formatPermissions1(List<Permission> allPermissions) {
		List<Map<String, Object>> result = new ArrayList<>();

		// 遍历所有权限数据，按层级组织
		for (Permission permission : allPermissions) {
			// 查找或创建一级权限
			Map<String, Object> level1 = findOrCreateLevel(permission.getLevel1Id(), permission.getLevel1Title(), result);

			// 查找或创建二级权限
			Map<String, Object> level2 = findOrCreateLevel(permission.getLevel2Id(), permission.getLevel2Title(), (List<Map<String, Object>>) level1.get("children"));
		}

		return result;
	}

	// 查找或创建一级或二级权限
	private Map<String, Object> findOrCreateLevel1(int id, String label, List<Map<String, Object>> parentList) {
		// 查找是否已经存在该权限
		for (Map<String, Object> level : parentList) {
			if ((int) level.get("id") == id) {
				return level;
			}
		}

		// 如果没有找到，则创建新的权限
		Map<String, Object> newLevel = new HashMap<>();
		newLevel.put("id", id);
		newLevel.put("label", label);
		newLevel.put("children", new ArrayList<Map<String, Object>>()); // 初始化 children
		parentList.add(newLevel);

		return newLevel;
	}
	private List<Map<String, Object>> formatPermissions2(List<Permission> allPermissions) {
		List<Map<String, Object>> result = new ArrayList<>();

		// 遍历所有权限数据，按层级组织
		for (Permission permission : allPermissions) {
			// 查找或创建一级权限
			Map<String, Object> level1 = findOrCreateLevel2(permission.getLevel1Id(), permission.getLevel1Name(),permission.getLevel1Src(), permission.getLevel1Src1(),permission.getLevel1Image(),result);

			// 查找或创建二级权限
			Map<String, Object> level2 = findOrCreateLevel1(permission.getLevel2Id(),permission.getLevel2Text(), permission.getLevel2Href(),permission.getLevel2Image(),(List<Map<String, Object>>) level1.get("children"));
		}

		return result;
	}

	// 查找或创建一级或二级权限
	private Map<String, Object> findOrCreateLevel2(int level1Id, String level1Name, String level1Src, String level1Src1, String level1Image, List<Map<String, Object>> parentList) {

		// 查找是否已经存在该权限
		for (Map<String, Object> level : parentList) {
			if ((int) level.get("id") == level1Id) {
				return level;
			}
		}

		// 如果没有找到，则创建新的权限
		Map<String, Object> newLevel = new HashMap<>();
		newLevel.put("id", level1Id);
		newLevel.put("src", level1Src);
		newLevel.put("src1", level1Src1);
		newLevel.put("image", level1Image);
		newLevel.put("name", level1Name);
		newLevel.put("children", new ArrayList<Map<String, Object>>()); // 初始化 children
		parentList.add(newLevel);

		return newLevel;
	}
	private Map<String, Object> findOrCreateLevel1(int level2Id, String level2Text, String level2Href, String level2Image, List<Map<String, Object>> parentList) {

		// 如果没有找到，则创建新的权限
		Map<String, Object> newLevel = new HashMap<>();
		newLevel.put("id", level2Id);
		newLevel.put("href", level2Href);
		newLevel.put("image", level2Image);
		newLevel.put("text", level2Text);
		parentList.add(newLevel);

		return newLevel;
	}
}
